//通过vue-router插件实现模板路由配置
import { createRouter, createWebHistory } from 'vue-router';
import nprogress from 'nprogress';
import 'nprogress/nprogress.css';
import { ElNotification } from 'element-plus';
import { constantRoute, asyncRoutes } from './routes';

import pinia from '@/store';
import { useUserStore } from '@/store/user';
let userStore = useUserStore(pinia);
//创建路由器
const router = createRouter({
  //路由模式hash
  history: createWebHistory(),
  routes: constantRoute,
  //滚动行为
  scrollBehavior() {
    return {
      left: 0,
      top: 0
    };
  }
});
//防止重复取数据
let hasGetInfo = false;
// 动态添加路由的方法
function addRoutes(menus) {
  // 是否有新的路由
  let hasNewRoutes = false;
  const findAndAddRoutesByMenus = arr => {
    arr.forEach(e => {
      let item = asyncRoutes.find(o => o.path == e.frontpath);
      if (item && !router.hasRoute(item.path)) {
        router.addRoute('admin', item);
        hasNewRoutes = true;
      }
      if (e.child && e.child.length > 0) {
        findAndAddRoutesByMenus(e.child);
      }
    });
  };

  findAndAddRoutesByMenus(menus);
  return hasNewRoutes;
}
router.beforeEach(async (to, from, next) => {
  //进度条
  nprogress.start();
  // 没有登录，强制跳转回登录页
  if (!userStore.token && to.path != '/login') {
    ElNotification({ type: 'error', message: '请先登录' });
    return next({ path: '/login' });
  }

  // 防止重复登录
  if (userStore.token && to.path == '/login') {
    ElNotification({ type: 'error', message: '请勿重复登录' });
    return next({ path: from.path ? from.path : '/' });
  }
  //判断是否登录 获取用户信息
  let hasNewRoutes = false;
  if (userStore.token && !hasGetInfo) {
    let menuRoutes = await userStore.getInfoAct();

    if (menuRoutes && menuRoutes.length > 0) {
      hasGetInfo = true;
      console.log(userStore.token, userStore.menuRoutes);
      // 动态添加路由
      hasNewRoutes = addRoutes(menuRoutes);
    }
  }

  // 设置页面标题
  let title = (to.meta.title ? to.meta.title : '') + '-帝莎编程商城后台';
  document.title = title;

  hasNewRoutes ? next(to.fullPath) : next();
});
// 全局后置守卫
router.afterEach((to, from) => {
  console.log(to, from);
  nprogress.done();
});
export default router;
